package com.hzdp.common;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RunnableCallable {

	static class RunnableC implements Runnable {
		@Override
		public void run() {
			System.out.println("In " + getClass());
		}
	}

	static class CallableC implements Callable<String> {

		@Override
		public String call() throws Exception {
			System.out.println("In " + getClass());
			return "OK";
		}

	}

	static class CallableE implements Callable<String> {

		@Override
		public String call() throws Exception {
			System.out.println("In " + getClass());
			throw new RuntimeException();
		}

	}

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newSingleThreadExecutor();
		executorService.execute(new RunnableC());
		Future<?> f1 = executorService.submit(new RunnableC());
		Object x1 = null;
		try {
			x1 = f1.get();
		} catch (InterruptedException | ExecutionException e1) {
			e1.printStackTrace();
		}
		System.out.println(x1);
		Future<String> f2 = executorService.submit(new CallableC());
		String x2 = null;
		try {
			x2 = f2.get(1000, TimeUnit.MILLISECONDS);
		} catch (InterruptedException | ExecutionException | TimeoutException e) {
			// 如果debug下CallableC,1秒后会抛出TimeoutException
			e.printStackTrace();
		}
		System.out.println(x2);

		Future<String> f3 = executorService.submit(new CallableE());
		String x3 = null;
		try {
			x3 = f3.get();
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println(x3);

	}
}
